package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.DeviceService;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.DeviceServiceService;
import com.iot.manage.service.TokenService;
import com.iot.manage.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 设备服务管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class DeviceIotServiceController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private DeviceServiceService deviceServiceService;

    /**
     * 查询设备服务信息列表
     *
     * @param token
     * @param query 模糊查询关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/findDeviceServiceList")
    public Result findDeviceServiceList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<DeviceService> deviceServiceList;
        int deviceServiceTotal;
        try{
            deviceServiceList = deviceServiceService.findDeviceServiceList(query,pagenum,pagesize);
            deviceServiceTotal = deviceServiceService.countDeviceServiceList(query);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",deviceServiceTotal);
        map.put("pagenum",pagenum);
        map.put("deviceServiceList",deviceServiceList);
        return result.build(map, Code.S200);
    }

    /**
     * 新增设备服务信息
     *
     * @param token
     * @param params 设备服务信息参数
     * @return
     */
    @PostMapping("/addDeviceServiceInfo")
    public Result addDeviceServiceInfo(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findDeviceServiceInfoByIdOrCode(token,params.getString("dserviceCode")).getData()){
                return result.build(null, Code.D411);
            }
            params.put("dserviceId", UUID.randomUUID().toString().replace("-", ""));
            params.put("dserviceArg", StringUtils.replaceBlank(params.get("dserviceArg").toString()));
            deviceServiceService.addDeviceServiceInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 根据设备服务ID或设备服务标识查询设备服务信息
     *
     * @param token
     * @param params 设备服务ID或设备服务标识
     * @return
     */
    @GetMapping("/findDeviceServiceInfoByIdOrCode/{params}")
    public Result findDeviceServiceInfoByIdOrCode(
            @RequestHeader("token") String token,
            @PathVariable("params") String params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        DeviceService deviceService;
        try{
            deviceService = deviceServiceService.findDeviceServiceInfoByIdOrCode(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(deviceService, Code.S200);
    }

    /**
     * 修改设备服务信息
     *
     * @param token
     * @param params 设备服务信息参数
     * @return
     */
    @PutMapping("/updateDeviceServiceInfo/{oldDserviceCode}")
    public Result updateDeviceServiceInfo(
            @RequestHeader("token") String token,
            @PathVariable("oldDserviceCode") String oldDserviceCode,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if (!(oldDserviceCode.equals(params.get("dserviceCode")))){
                if(null != findDeviceServiceInfoByIdOrCode(token,params.getString("dserviceCode")).getData()){
                    return result.build(null, Code.D411);
                }
            }
            params.put("dserviceArg", StringUtils.replaceBlank(params.get("dserviceArg").toString()));
            deviceServiceService.updateDeviceServiceInfo(params);
            params.put("oldDserviceCode",oldDserviceCode);
            deviceServiceService.updateDeviceModelArg(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *删除设备服务信息
     *
     * @param token
     * @param dserviceId 设备服务ID
     * @return
     */
    @DeleteMapping("/deleteDeviceServiceInfo/{dserviceId}/{dserviceCode}")
    public Result deleteDeviceServiceInfo(
            @RequestHeader("token") String token,
            @PathVariable("dserviceId") String dserviceId,
            @PathVariable("dserviceCode") String dserviceCode) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            int total = deviceServiceService.countServiceUseTotal(dserviceCode);
            if (total > 0){
                return result.build(null,Code.WARM);
            }
            deviceServiceService.deleteDeviceServiceInfo(dserviceId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }
}
